//  一个文本框 可以对应多个校验规则

/***********策略对象*********/

var strategies = {
    //不为空
    isNonEmpty : function (value,errorMsg){
        if(value === ''){
            return errorMsg
        }
    },
    //限制最小长度
    minLength : function (value, length, errorMsg){
        if( value.length < length){
            return errorMsg
        }
    },
    //限制号码
    isMobile : function (value ,errorMsg){
        if(!/(^1[3|5|8][0-9]{9}$)/.test(value)){
            return errorMsg
        }
    }
}

/*********Validator 对象 */

var Validator = function (){
    this.cache = [];
};
Validator.prototype.add = function( dom, rules){
    var self = this
    for(var i = 0, rule; rule = rules[i++];){
        (function(rule){
            var strategyAry = rule.strategy.split(':')
            var errorMsg = rule.errorMsg

            self.cache.push(function(){
                var strategy = strategyAry.shift();
                strategyAry.unshift( dom.value )
                strategyAry.push( errorMsg )
                return strategies[strategy].apply(dom, strategyAry)
            })
        })(rule)
    }
}

Validator.prototype.start = function () {
    var msg = []  //用于收集所有错误信息
    for(var i = 0;i<this.cache.length;i++){
        var oneMsg=this.cache[i]()
        if(oneMsg){
            msg.push(oneMsg)
        }
    }
    if(msg.length!==0){
        return msg
    }
}


/***************客户调用代码 */

var registerFrom = document.getElementById('registerForm')
var validataFunc = function () {
    var validator = new Validator();
    validator.add( registerFrom.userName, [{
        strategy:'isNonEmpty',
        errorMsg:'用户名不能为空'
    },{
        strategy:'minLength:6',
        errorMsg:'用户名长度不能小于6位'
    }])

    validator.add( registerFrom.paaaword,[{
        strategy:'minLength:10',
        errorMsg:'密码长度不能小于10位'
    }])

    var errorMsg = validator.start()
    return errorMsg
}
registerFrom.onsubmit = function(){
    var errorMsg = validataFunc();//收集所有错误信息
    if(errorMsg){
        console.log(errorMsg);//如果有错误信息 打印
        return false  //阻止表单提交
    }
}




